<template>
  <div>
    <div class="page-title">预约管理</div>
    
    <div class="card-container">
      <div class="search-form">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="会员姓名">
            <el-input v-model="searchForm.memberName" placeholder="请输入会员姓名" />
          </el-form-item>
          <el-form-item label="项目名称">
            <el-input v-model="searchForm.projectName" placeholder="请输入项目名称" />
          </el-form-item>
          <el-form-item label="状态" style="width: 150px;">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待确认" value="pending" />
              <el-option label="已确认" value="confirmed" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="预约日期">
            <el-date-picker
              v-model="searchForm.appointmentDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- <div class="table-operations">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增预约
        </el-button>
      </div> -->
      
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="memberName" label="会员姓名" width="120" />
        <el-table-column prop="memberPhone" label="手机号" width="120" />
        <el-table-column prop="projectName" label="项目名称" width="200" />
        <el-table-column prop="beauticianName" label="美容师" width="100" />
        <el-table-column prop="appointmentDate" label="预约时间" width="180">
        </el-table-column>
        <el-table-column prop="duration" label="时长(分钟)" width="100" />
        <el-table-column prop="notes" label="备注" width="300" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
            <el-button v-if="row.status === 'pending'" type="danger" text @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑预约弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editDialogTitle"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="会员姓名" prop="memberName">
          <el-input v-model="editForm.memberName" placeholder="请输入会员姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="memberPhone">
          <el-input v-model="editForm.memberPhone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="editForm.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="美容师" prop="beauticianName">
          <el-input v-model="editForm.beauticianName" placeholder="请输入美容师姓名" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentDate">
          <el-date-picker
            v-model="editForm.appointmentDate"
            type="date"
            placeholder="选择预约时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="时长(分钟)" prop="duration">
          <el-input-number
            v-model="editForm.duration"
            :min="30"
            :max="480"
            :step="30"
            placeholder="请输入时长"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="editForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitEdit" :loading="editLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { Appointment } from '@/types'
import { getAppointments, createAppointment, updateAppointment, deleteAppointment } from '@/api/appointments'

const searchForm = reactive({
  memberName: '',
  projectName: '',
  status: '',
  appointmentDate: null
})

const tableData = ref<Appointment[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref<FormInstance>()
const editDialogTitle = ref('编辑预约')

const editForm = reactive({
  id: 0,
  memberName: '',
  memberPhone: '',
  projectName: '',
  beauticianName: '',
  appointmentDate: '',
  duration: 60,
  status: 'pending' as 'pending' | 'confirmed' | 'completed' | 'cancelled',
  notes: ''
})

const editFormRules: FormRules = {
  memberName: [{ required: true, message: '请输入会员姓名', trigger: 'blur' }],
  memberPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  beauticianName: [{ required: true, message: '请输入美容师姓名', trigger: 'blur' }],
  appointmentDate: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  duration: [{ required: true, message: '请输入时长', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const loadData = async () => {
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    }
    const { records, total } = await getAppointments(params)
    tableData.value = records
    pagination.total = total
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.memberName = ''
  searchForm.projectName = ''
  searchForm.status = ''
  searchForm.appointmentDate = null
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadData()
}

const handleAdd = () => {
  // 跳转到新增预约页面
}

const handleEdit = (row: Appointment) => {
  // 填充编辑表单数据
  editForm.id = row.id
  editForm.memberName = row.memberName
  editForm.memberPhone = row.memberPhone
  editForm.projectName = row.projectName
  editForm.beauticianName = row.beauticianName
  editForm.appointmentDate = row.appointmentDate
  editForm.duration = row.duration
  editForm.status = row.status
  editForm.notes = row.notes || ''
  
  editDialogVisible.value = true
}

const handleSubmitEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        await updateAppointment(editForm)
        
        ElMessage.success('预约更新成功')
        editDialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('更新预约失败:', error)
        ElMessage.error('更新预约失败')
      } finally {
        editLoading.value = false
      }
    }
  })
}

const handleCloseDialog = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
}

const handleDelete = async (row: Appointment) => {
  try {
    await ElMessageBox.confirm(`确定要取消预约 【${row.projectName}】 吗？`, '提示', {
      type: 'warning'
    })
    await deleteAppointment(row.id)
    ElMessage.success('取消成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败:', error)
    }
  }
}

const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    confirmed: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  loadData()
})
</script>